package com.ls.rbac.security;

/**
 * created by liush on 2025/6/27
 **/


import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        AuthenticationResult authenticationResult = new AuthenticationResult(null,
                HttpStatus.FORBIDDEN.value(), "权限不足", null, null);
        String jsonString = JSON.toJSONString(authenticationResult);
        PrintWriter writer = response.getWriter();
        writer.write(jsonString);
        writer.close();
    }
}
